package com.sto.stoapp.http;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;

import android.content.Context;

import com.sto.stoapp.http.request.ServerSmsRequest;

public class ServerSmsHttpManager {

	// 请求返回成功
	private static final int RESPONSE_SUCCESS_CODE = 200;

	// 连接超时
	public static final int CONNECT_TIME_OUT = 30 * 1000;
	// 读超时时间
	public static final int READ_TIME_OUT = 60 * 1000;
	// 格式
	public static final String FORMAT = "utf-8";
	// 请求地址
	private static final String POST_ADDRESS_HEAD = "http://58.246.233.197/Sms/";

	private static final String POST_ADDRESS_TAIL = ".ashx";
	private final String PARAM = "args";

	// private Context context;

	/**
	 * 构造函数
	 */
	public ServerSmsHttpManager(Context context) {
		// this.context = context;
	}

	/**
	 * 服务器请求
	 * 
	 * @param address
	 *            请求地址
	 * @param entity
	 *            请求参数
	 * @return
	 */
	public String dopost(String address,ServerSmsRequest entity) {
		String strUTF8 = "";
		DefaultHttpClient client = new DefaultHttpClient();


		HttpPost httpPost = new HttpPost(address);

		client.getParams().setParameter(
				CoreConnectionPNames.CONNECTION_TIMEOUT, CONNECT_TIME_OUT);
		client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
				READ_TIME_OUT);

		ArrayList<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>();
		pairs.add(new BasicNameValuePair(PARAM, entity.getData()));
		try {
			httpPost.setEntity(new UrlEncodedFormEntity(pairs, FORMAT));
			HttpResponse response = client.execute(httpPost);
			if (response.getStatusLine().getStatusCode() == RESPONSE_SUCCESS_CODE) {
				String result = EntityUtils.toString(response.getEntity(),
						FORMAT);
				try {
					// 这是转成utf-8码
					strUTF8 = URLDecoder.decode(result, FORMAT);
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
			strUTF8=null;
		} 
		return strUTF8;
	}
}
